<template>
  <v-container fluid>
    <v-row justify="center">
      <v-col sm="4" md="4" lg="3">
        <v-card>
          <v-img src="../assets/login/background.png" class="white--text align-center" alt="登录">
            <v-card-title>Login</v-card-title>
          </v-img>
          <v-form ref="loginForm" v-model="valid" lazy-validation>
            <v-card-text>
              <v-text-field v-model="username" :rules="[usernameRules.required, usernameRules.isExist(usernameError)]" label="用户名" required>
              </v-text-field>
              <v-text-field v-model="password" :rules="[passwordRules.required, passwordRules.equal(passwordError)]" label="密码" required :append-icon="show ? 'mdi-eye' : 'mdi-eye-off'" @click:append="show = !show" :type="show ? 'text': 'password'">
              </v-text-field>
              <br/>
              <v-btn :disabled="!valid" color="primary" class="mr-4" v-on:click="validate">登录</v-btn>
              <v-btn color="default" class="mr-4" v-on:click="reset">重置</v-btn>
            </v-card-text>
          </v-form>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  name: 'Login',
  data: () => ({
    show: false,
    valid: true,
    username: '',
    usernameError: '',
    usernameRules: {
      required: v => !!v || '请输入用户名',
      isExist: (usernameError) => usernameError.length === 0 || usernameError
    },
    password: '',
    passwordError: '',
    passwordRules: {
      required: v => !!v || '请输入密码',
      equal: (passwordError) => passwordError.length === 0 || passwordError
    }
  }),
  methods: {
    validate () {
      const valid = this.$refs.loginForm.validate()
      if (valid) {
        this.$axios.post('rest_auth/login/', {
          username: this.username,
          password: this.password
        }).then(response => {
          console.log(response)
          // 请求成功，代表成功登录，设置token并且跳转到主页
          this.$store.commit('setToken', response.data.key)
          // 设置token的同时，尝试获取与该用户有关的信息，因为有token，所以无需传入参数
          this.$axios.get('rest_auth/user/')
            .then(response => {
              console.log(response)
              this.$store.commit('setUser', response.data)
            }).catch(error => {
              console.log(error)
            })
          this.$router.push({
            name: 'Home'
          })
        }).catch(error => {
          console.log(error)
          // 判断是用户名不存在，还是密码错误
          this.$axios.get('api/user/', {
            params: {
              username: this.username
            }
          }).then(response => {
            console.log(response)
            if (response.data.count === 0) {
              // 用户名不存在
              this.usernameError = '用户名不存在'
            } else {
              // 密码不正确
              this.passwordError = '密码不正确'
            }
            // 重新验证
            this.$refs.loginForm.validate()
          }).catch(error => {
            console.log(error)
          })
        })
      }
    },
    reset () {
      this.$refs.loginForm.reset()
    }
  },
  watch: {
    // 侦听器，每当用户名或密码改变时，就将错误变为空，以代表用户修改过错误
    username: function () {
      this.usernameError = ''
    },
    password: function () {
      this.passwordError = ''
    }
  }
}
</script>
